<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="订单编号" prop="businessCode">
        <el-input
          v-model="queryParams.businessCode"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="流程" prop="procId">
        <el-input
          v-model="queryParams.procId"
          placeholder="请输入流程"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择审批状态"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="事项" prop="shixiang">
        <el-select
        v-model="queryParams.shixiang"
        placeholder="请选择"
        class="!w-240px"
        @change="changeStatus"
      >
        <el-option 
        v-for="dict in statusLevel"
        :key="dict.value"
        :label="dict.label"
        :value="dict.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="业务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入业务名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="维修类型" prop="repairStatus">
        <el-select
          v-model="queryParams.repairStatus"
          placeholder="请选择维修类型"
          clearable
          class="!w-240px"
        >
          <el-option 
          v-for="dict in getStrDictOptions(DICT_TYPE.eam_repair_type)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
          />
        </el-select>
        <!-- <el-radio-group v-model="queryParams.repairStatus">
          <el-radio  v-for="dict in getStrDictOptions(DICT_TYPE.eam_repair_type)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value">{{dict.label}}</el-radio> 
        </el-radio-group> -->
      </el-form-item>
      <!-- <el-form-item label="故障内容" prop="categoryTplId">
        <el-input
          v-model="queryParams.categoryTplId"
          placeholder="请输入故障内容"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="维修类型" prop="repairType">
        <el-select
          v-model="queryParams.repairType"
          placeholder="请选择维修类型"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="紧急程度" prop="urgencyId">
        <el-input
          v-model="queryParams.urgencyId"
          placeholder="请输入紧急程度"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="报修部门" prop="reportOrgId">
        <el-input
          v-model="queryParams.reportOrgId"
          placeholder="请输入报修部门"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="计划完成日期" prop="planFinishDate">
        <el-date-picker
          v-model="queryParams.planFinishDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="报修人员" prop="reportUserId">
        <el-select filterable v-model="queryParams.reportUserId" class="!w-240px" placeholder="报修人员" clearable>
          <el-option
            v-for="(user, index) in userList"
            :label="user.nickname"
            :value="user.id"
            :key="index"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维修费用" prop="repairCost">
        <el-input
          v-model="queryParams.repairCost"
          placeholder="请输入维修费用"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="图片" prop="pictureId">
        <el-input
          v-model="queryParams.pictureId"
          placeholder="请输入图片"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <!-- <el-form-item label="制单人员" prop="originatorId">
        <el-input
          v-model="queryParams.originatorId"
          placeholder="请输入制单人员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="业务日期" prop="businessDate">
        <el-date-picker
          v-model="queryParams.businessDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="维修单" prop="autoAct">
        <el-input
          v-model="queryParams.autoAct"
          placeholder="请输入维修单"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建规则" prop="autoActRule">
        <el-input
          v-model="queryParams.autoActRule"
          placeholder="请输入创建规则"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="故障设备" prop="assetId">
        <el-input
          v-model="queryParams.assetId"
          placeholder="请输入故障设备"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eam:repair-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eam:repair-order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="流程" align="center" prop="procId" />
      <!-- <el-table-column label="审批状态" align="center" prop="status" /> -->
      <!-- <el-table-column label="业务名称" align="center" prop="name" /> -->
      <el-table-column label="维修状态" align="center" prop="repairStatus" />
      <el-table-column label="维修类型" align="center" prop="repairType" />
      <!-- <el-table-column label="维修类型" align="center" prop="repairType" /> -->
      <el-table-column label="紧急程度" align="center" prop="urgencyId" />
      <el-table-column label="报修部门名称" align="center" prop="reportOrgName" />
      <el-table-column label="计划完成日期" align="center" prop="planFinishDate" />
      <el-table-column label="报修人员名称" align="center" prop="reportUserName" />
      <el-table-column label="维修人员名称" align="center" prop="repairUserName" />
      <!-- <el-table-column label="维修费用" align="center" prop="repairCost" /> -->
      <!-- <el-table-column label="报修内容" align="center" prop="content" /> -->
      <!-- <el-table-column label="图片" align="center" prop="pictureId" />
      <el-table-column label="制单人员" align="center" prop="originatorId" />
      <el-table-column label="业务日期" align="center" prop="businessDate" />
      <el-table-column label="维修单" align="center" prop="autoAct" />
      <el-table-column label="创建规则" align="center" prop="autoActRule" /> -->
      <el-table-column label="故障设备" align="center" prop="assetName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="180px">
        <template #default="scope">
          <el-button
            v-if="queryParams.shixiang === 0"
            link
            type="primary"
            @click="openForm('update', scope.row.id, scope.row.taskId)"
            v-hasPermi="['eam:repair-order:update']"
          >
            审核
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['eam:repair-order:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RepairOrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as RepairOrderApi from '@/api/eam/repairorder'
import RepairOrderForm from './RepairOrderForm.vue'
import {  handleTree } from '@/utils/tree'
import * as UserApi from '@/api/system/user'

defineOptions({ name: 'RepairOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  shixiang: 0,
  pageNo: 1,
  pageSize: 10,
  businessCode: null,
  procId: null,
  status: null,
  name: null,
  repairStatus: null,
  categoryTplId: null,
  repairType: null,
  urgencyId: null,
  reportOrgId: null,
  planFinishDate: [],
  reportUserId: null,
  repairCost: null,
  content: null,
  pictureId: null,
  originatorId: null,
  businessDate: [],
  autoAct: null,
  autoActRule: null,
  assetId: null,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const statusLevel = [
    {
      label: '代办事项',
      value: 0,
    },
    {
      label: '已办事项',
      value: 1,
    },
    // {
    //   label: '全部',
    //   value: 2,
    // },
  ];

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    let data: any = ''
    console.log(queryParams, 'queryParams')
    if (queryParams.shixiang === 0) {
        // data = (await RepairOrderApi.RepairOrderTodoPage(queryParams)) || {};
        data = (await RepairOrderApi.RepairOrderTodoPage(queryParams)) || {};
      } else if (queryParams.shixiang === 1) {
        data = (await RepairOrderApi.RepairOrderDonePage(queryParams)) || {};
      } else if (queryParams.shixiang === 2) {
        data = (await RepairOrderApi.getRepairOrderPage(queryParams)) || {};
      }
    // const data = await RepairOrderApi.getRepairOrderPage(queryParams)
    list.value = data?.list?.map(item => {
      // 假设 item.status 是数字，你需要根据它在字典里找到对应的 name
      const statusDict = getIntDictOptions(DICT_TYPE.eam_repair_status).find(dict => dict.value === Number(item.repairStatus))
      // 如果找到对应的字典项，则返回 name，否则保持原样
      item.repairStatus = statusDict?.value ? statusDict.label : item.repairStatus

      const repairTypeObj = getIntDictOptions(DICT_TYPE.eam_repair_type).find(dict => dict.value === Number(item.repairType))
      // 如果找到对应的字典项，则返回 name，否则保持原样
      item.repairType = repairTypeObj?.value ? repairTypeObj.label : item.repairType
      
      const urgencyIdObj = getIntDictOptions(DICT_TYPE.eam_emergency_type).find(dict => dict.value === Number(item.urgencyId))
      // 如果找到对应的字典项，则返回 name，否则保持原样
      item.urgencyId = urgencyIdObj?.value ? urgencyIdObj.label : item.urgencyId

      return item
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  console.log("2333")
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, taskId?: number ) => {
  console.log(type, id, taskId,  queryParams.shixiang)
  formRef.value.open(type, id, taskId, queryParams.shixiang)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RepairOrderApi.deleteRepairOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RepairOrderApi.exportRepairOrder(queryParams)
    download.excel(data, '故障申请单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const changeStatus = () => {
    // if (formModel.value?.status === 1 || formModel.value?.status === 2) {
    //   if (columns.value.length === 14) {
    //     columns.value?.splice?.(-1, 0, {
    //       title: '当前处理人',
    //       dataIndex: 'assignName',
    //     });
    //   }
    // } else {
    //   console.log(columns.value.length, 'columns.value.length');
    //   if (columns.value.length === 15) {
    //     columns.value?.splice?.(-2, 1);
    //   }
    // }

    handleQuery();
  };

/** 初始化 **/
const userList = ref<UserApi.UserVO[]>([]) // 全量用户清单
onMounted(async () => {
  userList.value = handleTree(await UserApi.getSimpleUserList())
  getList()
})
</script>